// action.java
package org.zjx.action;

import lombok.Getter;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zjx.manager.ActivationManager;
import org.zjx.state.StateManager;
import org.zjx.core.IWindow;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 命令抽象基类 - 改进中断处理和资源管理
 */
@Getter
public abstract class Action implements IAction {
    private static final Logger logger = LoggerFactory.getLogger(Action.class);
    protected final StateManager stateManager;
    protected final IWindow targetWindow;
    private final String actionName;
    private final boolean requiresActiveWindow;
    private final AtomicBoolean executed = new AtomicBoolean(false);

    public Action(IWindow targetWindow, boolean requiresActiveWindow) {
        if (targetWindow == null) {
            throw new IllegalArgumentException("目标窗口不能为空");
        }
        this.targetWindow = targetWindow;
        this.requiresActiveWindow = requiresActiveWindow;
        this.actionName = this.getClass().getSimpleName();
        this.stateManager = targetWindow.getState();
    }

    @SneakyThrows
    @Override
    public final boolean execute(){
        // 防止重复执行
        if (!executed.compareAndSet(false, true)) {
            logger.warn("[命令] 命令已被执行，跳过: {}", actionName);
            return false;
        }

        try {
            // 如果需要激活权，使用新的 ActivationManager
            if (requiresActiveWindow && !targetWindow.isActive()) {
                executed.set(false);
                ActivationManager.executeWithActivation(this);
            } else {
                // 不需要激活权的命令直接执行
                doExecute();
            }
            return true;
        } catch (RuntimeException e) {
            logger.error("[命令] 执行失败: {}", actionName, e);
            return false;
        }
    }

    /**
     * 检查中断状态
     */
    protected final void checkInterruption() throws InterruptedException {
        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException("线程被中断");
        }
    }

    /**
     * 检查是否被中断
     */
    protected final boolean isInterrupted() {
        return Thread.currentThread().isInterrupted();
    }

    /**
     * 具体的命令执行逻辑
     */
    protected abstract void doExecute() throws Exception;
}